import * as PIXI from 'pixi.js'
import { setPixi } from '@renderer/store/modules/usePixiStore'
import { skillConsumeModule } from '@renderer/utils/bundle'
import useDiyStore from '@renderer/store/modules/useDiyStore'
export default async (): Promise<PIXI.Container<PIXI.ContainerChild>> => {
  const diyStore = useDiyStore()
  const container = new PIXI.Container()
  const text = new PIXI.Text({
    text: diyStore.creationData.ability,
    alpha: 0.9,
    style: {
      fontFamily: 'XQFont',
      fontSize: diyStore.creationData.transform.abilityFontSize,
      fill: 0xffffff,
      align: 'center',
      lineHeight: diyStore.creationData.transform.abilityFontSize,
    },
  })
  text.anchor.set(0.5)
  // 文本有多少行
  const rowNum = diyStore.creationData.ability.split('').filter((char) => char === '\n').length
  container.addChild(text)
  const pattern = /\{\{TP(\d+|\?)\}\}/
  const match = diyStore.creationData.ability.match(pattern) as Array<string>
  if (match) {
    let skillConsume = match[1] as Wx.Card.SKILL_CONSUME
    if (skillConsume === '?' || Number(skillConsume) > 8) {
      skillConsume = '?'
    }
    const point = { x: 0, y: 0 }
    const newText = diyStore.creationData.ability.replace(match[0], (_r, i) => {
      // 图标之前后多少个换行符, 即图标所在行的下标
      const beforeRowNum = diyStore.creationData.ability
        .substring(0, i)
        .split('')
        .filter((char) => char === '\n').length
      // 所在行的内容
      const rowStr = diyStore.creationData.ability.split('\n')[beforeRowNum]
      // 所在行的图标之后的内容
      const afterRowStr = diyStore.creationData.ability.substring(i).split('\n')[0]
      // 计算文本宽度
      const tempText = new PIXI.Text({
        text: rowStr,
        style: { fontSize: diyStore.creationData.transform.abilityFontSize },
      })
      const temp2Text = new PIXI.Text({
        text: afterRowStr,
        style: { fontSize: diyStore.creationData.transform.abilityFontSize },
      })
      const place = '     '
      const temp3Text = new PIXI.Text({
        text: place,
        style: { fontSize: diyStore.creationData.transform.abilityFontSize },
      })
      point.x = tempText.width / 2 - temp2Text.width + temp3Text.width
      point.y = beforeRowNum - rowNum / 2
      return place
    })
    const sprite = await skillConsumeModule({ skillConsume })
    sprite.anchor.set(0.5)
    sprite.scale.set((diyStore.creationData.transform.abilityFontSize / 28) * 0.64)
    sprite.position.set(point.x, point.y * sprite.height)
    text.text = newText
    container.addChild(sprite) // 文字的中轴在文字区域的中间部分
  }
  container.position.set(0, 506 / 2 - 126 + 8)
  setPixi(container.uid, container)
  diyStore.setUidMap('ability', container.uid)
  return container
}
